﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace SharePoint.Contrib.Extensions
{
    /// <summary>
    /// Extension methods for the SPFieldCollection class
    /// </summary>
    public static class SPFieldCollectionExtensions
    {

        /// <summary>
        /// Converts a field in the collection to the preferred SPField type.
        /// </summary>
        /// <param name="name">The internal name of the field</param>
        public static T Field<T>(this SPFieldCollection instance, string name) where T : SPField
        {
            T field = default(T);

            if (instance.Contains(name))
            {
                field = instance.GetFieldByInternalName(name) as T;
            }

            return field;
        }

        /// <summary>
        /// Determines whether the specified field can be found in the collection.
        /// </summary>
        /// <param name="id">The id of the field to find.</param> 
        public static bool Contains(this SPFieldCollection instance, Guid id)
        {
            return instance
                    .Contains(spf => spf.Id == id);

        }

        /// <summary>
        /// Determines whether the specified field can be found in the collection.
        /// </summary>
        /// <param name="name">The internal name of the field to find.</param> 
        public static bool Contains(this SPFieldCollection instance, string name)
        {
            return instance
                    .Contains(spf => spf.InternalName == name);

        }

        /// <summary>
        /// Determines whether the specified field can be found in the collection.
        /// </summary>
        /// <param name="func">The delegate to use to search</param>
        public static bool Contains(this SPFieldCollection instance, Func<SPField, bool> match)
        {
            return instance
                    .Cast<SPField>()
                    .Any(match);

        }
    }
}
